<template>
  <div>
    <div v-if="loading">In the process of logging in...</div>
    <div v-else-if="error">Something is wrong：{{ error.message }}</div>
    <div v-else>Login successful! Redirecting now....</div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { useAuth0 } from '@auth0/auth0-vue'
import { useAuthStore } from '@/store'
import { useRouter } from 'vue-router'

const {
  getAccessTokenSilently,
  handleRedirectCallback,
  user,
  isAuthenticated,
  logout,
} = useAuth0()
const authStore = useAuthStore()
const router = useRouter()

const loading = ref(true)
const error = ref()

onMounted(async () => {
  try {
    // 处理登录回调
    try {
      // await handleRedirectCallback()
      const token = await getAccessTokenSilently()
      console.log('Token:', token)
      console.log("isAuthenticated.value && user.value:",isAuthenticated.value && user.value);
      // 如果用户已登录，同步用户状态到 Pinia Store
      if (isAuthenticated.value && user.value) {
        authStore.setAuthState(true, user.value)
      }

      // 跳转到首页或其他页面
      router.push('/')
    } catch (error) {
      console.error('获取令牌失败:', error)
    }
  } catch (e) {
    error.value = e
    console.error('登录失败：', e)
  } finally {
    loading.value = false
  }
})
</script>
